package edu.scau.pos.service;

import edu.scau.core.util.ServletUtils;
import edu.scau.pos.domain.Category;
import edu.scau.pos.mapper.CategoryMapper;
import edu.scau.pos.vo.CategoryVo;
import edu.scau.system.domain.LoginUser;
import edu.scau.system.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService{
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private TokenService tokenService;
    @Override
    public List<CategoryVo> listAll() {
        return categoryMapper.listAll();
    }

    @Override
    public CategoryVo findCategoryById(Long id) {
        return categoryMapper.findCategoryById(id);
    }

    @Override
    public List<CategoryVo> listByPage(CategoryVo category) {
        return categoryMapper.listByPage(category);
    }

    @Override
    public int updateCategory(CategoryVo categoryVo) {
        int is_deleted=0;
        LoginUser loginUser=tokenService.getLoginUser(ServletUtils.getRequest());
        String updateBy=loginUser.getUsername();
        Date updateTime=new Date();
        Category category=new Category(categoryVo);
        category.setIs_deleted(is_deleted);
        category.setUpdateBy(updateBy);
        category.setUpdateTime(updateTime);
        return categoryMapper.updateCategory(category);
    }

    @Override
    public int deleteCategoryById(Long id) {
        return categoryMapper.deleteCategoryById(id);
    }

    @Override
    public int insertCategory(CategoryVo categoryVo) {
        int is_deleted=0;
        LoginUser loginUser=tokenService.getLoginUser(ServletUtils.getRequest());
        String createBy=loginUser.getUsername();
        Date createTime=new Date();
        Category category=new Category(categoryVo);
        category.setIs_deleted(is_deleted);
        category.setCreateBy(createBy);
        category.setCreateTime(createTime);
        return categoryMapper.insertCategory(category);
    }

    /**
     * 分类是否存在
     * @param categoryId
     * @return true 存在
     */
    @Override
    public boolean isExisted(long categoryId) {
        return categoryMapper.isExisted(categoryId)>0;
    }
}
